<template>
	<!-- 提交订单 -->
	<view class="container">
		
		<view class="yh-pd30">
		
			<view  v-if="!addressInfo" style="float: left;margin-top: 30rpx;;height: 50px;line-height:50px;background: red;width: 94%;margin-left: 3%;border-radius: 0.5em;background: #fff;"
			 @click="pageJumps('/pages/index/select1')"
				class="yh-h88 level_align flex_between yh-bgf yh-fc000 yh-fz28 yh-br12 yh-ptb0lr30">
				<view class="ellispsis1 flex-1 yh-mr20" style="float: left;margin-left: 20rpx;">
					请选择收货地址
				</view>
				<uni-icons style="float: right;margin-right: 20rpx;" type="arrowright" size="18" color="#999999"></uni-icons>
			</view>
			
			<view v-else @click="pageJumps('/pages/index/select1')"
			style="float: left;padding-left:10px ;;margin-top: 30rpx;padding-bottom:40rpx;background: red;width: 94%;margin-left: 3%;border-radius: 0.5em;background: #fff;"
				class="yh-bgf yh-bs-tc level_align flex_between yh-mt20 yh-pd30;">
				<view class="">
				
					<view class="yh-fc666 yh-mt10 yh-lh44" style="margin-top: 15px;">
					{{addressInfo.userName}}
					{{addressInfo.userPhone}}
					
					</view>
					<view>
						{{addressInfo.address}}
					</view>
				</view>
				<!-- 待支付订单可以选择地址 -->
				<!-- <uni-icons type="arrowright" size="18" color="#999"></uni-icons> -->
			</view>

			<view v-if="info" class="yh-mt20" style="float: left;padding-bottom: 20px;;padding-top: 15px;;margin-top: 30rpx;background: red;width: 94%;margin-left:3%;padding-left:3%;border-radius: 0.5em;background: #fff;">
				<view class="level_align flex_between yh-pd30 yh-bgf yh-bdbm yh-br-t-lr12">
					<view class="yh-mr30 yh-pr" style="float: left;">
					
							<image style="height: 100px;width:100px;padding: 20rpx;border-radius: 0.5em;" class="yh-w160 yh-h160" :src="info.images" mode="">
							</image>
					</view>
					
					<view class="flex flex_column flex-1" >
						<view style="font-weight: 700;width: 99%;float: left;" class="yh-fc333 yh-fz32 yh-fw600 ellispsis2 yh-lh44">
							{{info.title}}
						</view>
					
					</view>
				</view>

				<view class="level_align flex_between yh-ptb0lr30 yh-h88 yh-bgf yh-br-b-lr12" style="margin-top: 20px;">
					
					<view class="yh-red" style="color: red;">
						￥{{info.money}}
						
						<view style="float: right;margin-right: 10px;">
							<tui-numberbox :min="1" :max="100" :value="num" @change="change">
							</tui-numberbox>
						</view>
										
					</view>
					
				
					
				</view>
			</view>

			<view class="yh-mt20" style="float: left;padding-top: 15rpx;padding-bottom: 15rpx;;margin-top: 30rpx;background: red;width: 94%;margin-left:3%;padding-left:3%;border-radius: 0.5em;background: #fff;">
			
				<view class="level_align flex_between yh-ptb0lr30 yh-h88 yh-bgf yh-br-b-lr12">
					<view class="" style="float: left;">
						运费
					</view>
					<view class="yh-fc999" style="float: right;margin-right: 30rpx;">
					免运费
					</view>
				</view>
			
			</view>

			<view class="yh-br12 yh-bgf yh-pd30 yh-mt20" style="float: left;padding-top: 15rpx;padding-bottom: 35rpx;;margin-top: 30rpx;background: red;width: 94%;margin-left:3%;padding-left:3%;border-radius: 0.5em;background: #fff;">
				<view class="yh-fw600 yh-fz32 yh-lh54" style="font-weight: 700;">
					备注
				</view>
				<view class="yh-mt10" style="margin-top: 20rpx;">
					<textarea value="" style="height: 200rpx;background: #f1f1f1;width: 95%;padding: 10px;" v-model="beizhu" placeholder="备注信息"
						class="yh-bcF5 yh-w100 yh-pd20" />
				</view>
			</view>
		

		</view>


		<view style="width: 100%;background: #fff;height: 50px;line-height: 50px;position: fixed;bottom: 0px;" class="yh-btn-h100 level_align flex_between yh-bgf yh-h102 yh-bdtp yh-ptb0lr30">
			<view class="level_align yh-fc999" style="float: left;margin-left: 15px;">
				<text class="yh-fc999">合计：</text><text class="yh-red yh-fz36">￥ {{money}}</text>
			</view>
			<tui-button style="float: right;margin-right: 15px;margin-top: 5px;background: #3d3d3d;" @click="btnPay1" width="200rpx" height="70rpx" :size="28" type="danger" shape="circle">提交订单
			</tui-button>
		</view>


	</view>
</template>

<script>
	import tSelectCoupons from "@/components/t-select-coupons/t-select-coupons"
	import selectPay from '@/components/selectPay.vue'
	export default {
		components: {
			tSelectCoupons,
			selectPay
		},
		data() {
			return {
				money:0,
				info:null,
				num:1,
				id:0,
				hasCoupon: true, // 有优惠券
				couponShow: false, // 优惠券弹框
				couponList: [], // 可用优惠券列表
				couponInfo: {}, // 选择的优惠券
				// curPayType: 'balance', // 当前支付方式：balance余额 | 微信wechat | 支付宝alipay
				goodsInfo: {}, // 商品基本信息
				select_sp_ids: [], // 选择的规格id
				spGoodsInfo: {}, // 选择的规格信息
				spec_attr: {}, // // 规格列表

				addressInfo: [], // 地址信息
				beizhu: '', // 备注
				emsMoney: 0, // 运费
				color1:"background: #3d3d3d;",
				color2:"background: #cecece;",
				clone_index:1

			};
		},
		onLoad(opt) {
			this.id = opt.id;
		},
		onShow() {
			this.get_info();
			this.adds();
		},
		onUnload() {
			uni.removeStorageSync('temporary_adderss')
			uni.removeStorageSync('url')
		},
		computed: {
			totalMoney() {
				let money = 0,
					goods_price = 0;
				if (this.spGoodsInfo.form && this.spGoodsInfo.form.goods_price) {
					money = Number(this.spGoodsInfo.form.goods_price) * Number(this.goodsInfo.value)
				}
				money += Number(this.emsMoney)
				if (this.couponInfo.id) {
					money -= Number(this.couponInfo.number)
				}
				return money
			}
		},
		methods: {
			btnPay1(){
				if(!this.addressInfo){
					uni.showToast({
						title: '请先选择地址',
						icon: 'none'
					});
					return;
				}
				
				
				let platform = uni.getSystemInfoSync().platform;
				if(platform === 'ios'){
					  // 苹果
					uni.showLoading({ title: '正在加载', mask: true });
					var _this = this;
					_this.$api.request('/api/user/wxppay2', {
						tian:this.money,
					}, uni.getStorageSync('token'), function(res) {
						console.log(res,888888);
						uni.hideLoading();
						if (res.code == 1) {
							console.log(res.data.data,7777777)
							uni.requestPayment({
								"provider": "appleiap", 
								"orderInfo": res.data,
								success(res) {
									_this.popupClose();	
									uni.showToast({
										title: '支付完成',
										icon: 'none'
									});
									setTimeout(function(){
										_this.get_info();
										//支付完成
										if(_this.time_m){
											clearInterval(_this.time_m)
										}
										_this.renwu();
									},500)
									
								},
								fail(e) {
									console.log(e,"Err")
								}
							})
						}
					});
				} else if(platform === 'android'){
				  // 安卓
					uni.showLoading({ title: '正在加载', mask: true });
					var _this = this;
					_this.$api.request('/api/user/wxppay1', {
						tian:this.money,
					}, uni.getStorageSync('token'), function(res) {
						console.log(res,888888);
						uni.hideLoading();
						if (res.code == 1) {
							console.log(res.data,7777777)
							uni.requestPayment({
								"provider": "wxpay", 
								"orderInfo": res.data,
								success(res) {
									_this.popupClose();	
									uni.showToast({
										title: '支付完成',
										icon: 'none'
									});
									setTimeout(function(){
										_this.get_info();
										//支付完成
										if(_this.time_m){
											clearInterval(_this.time_m)
										}
										_this.renwu();
									},500)
									
								},
								fail(e) {}
							})
						}
					});
				} else {
					//
					let that = this;
					uni.login({
					    provider: 'weixin',
					    success: function (loginRes) {
					        // 登录成功
							that.$api.request('/api/user/wxppay3', {tian:that.money,code:loginRes.code},
							 '', function(res){
								console.log(res);
									
								if(res.code == 1) {
										console.log(res.data,77777777);
									uni.requestPayment({
									    provider: 'wxpay',
									    timeStamp: String(res.data.timeStamp),
									    nonceStr: String(res.data.nonceStr),
									    package:String( res.data.package),
									    signType: 'MD5',
									    paySign: String(res.data.paySign),
									    success:  (res)=> {
												this.$refs.popup.close()
												uni.switchTab({
												   url: '../index/index'
												});
									    },
									    fail: function (err) {
									        console.log('fail:' + JSON.stringify(err));
									    }
									});
									
								
								}else{
									uni.showToast({
										title: res.msg,
										icon: 'none'
									})
								}
							});
					    },
					    fail: function (err) {
					        // 登录授权失败  
					        // err.code是错误码
					    }
					});
					
			
				
			
						
					
					
				
				}			
			},
			pageJumps(url){
					uni.navigateTo({ url:url});
			},
			clone_type(type){
				this.clone_index = type;
				this.color1 = "background: #cecece;";
				this.color2 = "background: #cecece;";
				if(type == 1){
					this.color1 = "background: #3d3d3d;";
				}else{
					this.color2 = "background: #3d3d3d;";
				}
			},
			adds(){
				let id = uni.getStorageSync('aid')
				uni.showLoading({ title: '正在加载', mask: true });
				var _this = this;
				_this.$api.request('/api/user/adds', {id:id}, uni.getStorageSync('token'), function(res) {
					uni.hideLoading();
					if (res.code == 1) {
					console.log(res.data,7777777)
						_this.addressInfo = res.data
						
					}
					uni.hideLoading();
				});
			},
			get_info(){
				
				uni.showLoading({ title: '正在加载', mask: true });
				var _this = this;
				_this.$api.request('/api/index/getShopDea1', {id:_this.id}, uni.getStorageSync('token'), function(res) {
					uni.hideLoading();
					if (res.code == 1) {
					
						let richtext =  res.data.content;
						const regex = new RegExp('<img', 'gi');
						richtext = richtext.replace(regex,'<img style="width: 100%;"');
						//再不济，加上这个
						const regex1 = new RegExp('data-fail="0" style="', 'gi');
						richtext = richtext.replace(regex1,'data-fail="0" style="width: 100%;');
						 res.data.content = richtext
					
						_this.info = res.data;
						_this.imgList = res.data.img_arr;
						_this.money = _this.info.money 
						
					}
					uni.hideLoading();
				});
			},
			// 数量加减
			change: function(e) {
				console.log(e,777777)
				this.num = e.value
				
				this.money = this.info.money * this.num
				// this.goodsInfo.value = e.value;
				// this.getCouponList()
			},
			// 获取可用优惠券
			getCouponList() {
				let goods_price = 0;
				if (this.spGoodsInfo.form.goods_price) {
					goods_price = Number(this.spGoodsInfo.form.goods_price) * Number(this.goodsInfo.value)
				}
				// goods_price = this.spGoodsInfo.form && this.spGoodsInfo.form.goods_price && this.spGoodsInfo.form.goods_price && Number(this.spGoodsInfo.form.goods_price)
				let money = goods_price * Number(this.goodsInfo.value) + Number(this.emsMoney)
				this.$http.get(this.$api.couponGetList, {
					is_used: 1,
					page: 1,
					size: 100,
					money: money
				}).then(res => {
					if (res.code === 1) {
						this.couponList = res.data.data
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			// 获取运费
			getEmsMoney() {
				this.$http.get(this.$api.ems_money, {
					aid: this.addressInfo.address_id && this.addressInfo.address_id,
				}).then(res => {
					if (res.code === 1) {
						this.emsMoney = res.data.money || 0
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			
			// 获取默认地址
			getGetdefaultAddress() {
				this.$http.get(this.$api.addressGetdefault).then(res => {
					if (res.code === 1) {
						if (res.data) {
							this.addressInfo = res.data
							this.getEmsMoney()
						}
						
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			selectCoupon(e) {
				this.couponInfo = e
			},
			// 点击提交
			btnPay() {
				console.log(888888888,this.clone_index,this.addressInfo)
				if(this.clone_index == 2 && this.addressInfo == null && !this.addressInfo.address_id){
							
					return uni.showToast({
						title: '请选择地址',
						icon: 'none'
					})
			
				}
				
				this.$refs.selectPayPop.open()
			},
			// 取消支付，生成待支付订单，去订单列表
			closePay() {
				this.pageJumps('/pages/mine/orderList')
			},
			// 确认支付，成功之后去订单列表
			payConfirm({payType,code}) {
				uni.showLoading({
					title: '加载中...'
				})
				var address_id = 0;
				
				if(this.addressInfo && this.addressInfo != null){
					address_id = this.addressInfo.address_id
				}
				this.$http.post(this.$api.buyNowPay, {
					goods_id: this.goodsInfo.id,
					goods_num: this.goodsInfo.value,
					goods_sku_id: this.spGoodsInfo.goods_spec_id,
					coupon_id: this.couponInfo.id && this.couponInfo.id || '',
					type: payType,
					beizhu: this.beizhu,
					code:code,
					card_id:uni.getStorageSync('bankMessage').id,
					clone_index:this.clone_index,
					aid: address_id,
				}).then(res => {
					uni.hideLoading()
					if (res.code === 1) {
						let pay = res.data
						if (payType === 'wx') {
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: pay.timeStamp,
								nonceStr: pay.nonceStr,
								package: pay.package,
								signType: pay.signType,
								paySign: pay.paySign,
								success: (res) => { // 微信支付成功就跳转详情
									uni.showToast({
										title: res.msg,
										icon: 'success',
										mask: true
									})
									setTimeout(() => {
										uni.reLaunch({
											url: '/pages/mine/myOrderList'
										})
										// this.pageJumps('/pages/mine/myOrderList')
									}, 600)
								},
								fail(err) {
									uni.showToast({title:'取消支付',icon:'none'})
									setTimeout(()=>{
										uni.reLaunch({
											url: '/pages/mine/myOrderList'
										})
									},800)
									console.log('fail:' + JSON.stringify(err));
								}
							});
						} else if (payType === 'wxapp') {
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo: pay,
								success: () => {
									uni.showToast({
										title: res.msg,
										icon: 'success',
										mask: true
									})
									setTimeout(() => {
										uni.reLaunch({
											url: '/pages/mine/myOrderList'
										})
										// uni.redirectTo({
										// 	url: "/pages/mine/myOrderList"
										// })
									},800)
								},
								fail: (res) => {
									uni.showToast({title:'取消支付',icon:'none'})
									setTimeout(()=>{
										uni.reLaunch({
											url: '/pages/mine/myOrderList'
										})
									},800)
								}
							})
						} else if (payType === 'zfb') { // 支付宝支付
						
						
						
							uni.requestPayment({
								provider: 'alipay',
								orderInfo: pay,
								success: () => {
									uni.showToast({
										title: res.msg,
										icon: 'success',
										mask: true
									})
									setTimeout(() => {
										uni.reLaunch({
											url: '/pages/mine/myOrderList'
										})
										// uni.redirectTo({
										// 	url: "/pages/mine/myOrderList"
										// })
									},800)
								},
								fail: (res) => {
									uni.showToast({title:'取消支付',icon:'none'})
									setTimeout(()=>{
										uni.reLaunch({
											url: '/pages/mine/myOrderList'
										})
									},800)
									console.log('支付错误', JSON.stringify(res));
								}
							})
						} else if (payType === 'yhk') {
							if (res.code === 1) {
								uni.showToast({
									title: res.msg,
									icon: 'success',
									mask: true
								})
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/mine/myOrderList'
									})
								},800)
							}
							// this.$http.post(this.$api.kaishizhifu,{
							// 	code:'',
							// 	id:uni.getStorageSync('bankMessage').id,
							// 	money:this.totalMoney,
							// 	beizhu: this.beizhu,
							// 	coupon_id: this.couponInfo.id && this.couponInfo.id || '',
							// 	aid: this.addressInfo.address_id && this.addressInfo.address_id,
							// })
							// uni.setStorageSync('url',res.data.web_url)
							// uni.navigateTo({url:'/pages/home/web'})
						}
						else {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								mask: true
							})
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/mine/myOrderList'
								})
								// this.pageJumps('/pages/mine/myOrderList')
							}, 600)
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})

			},
			// wxApplet 微信小程序支付
			wxApplet(payType) {
				this.$http.post(this.$api.buyNowPay, {
					goods_id: this.goodsInfo.id,
					goods_num: this.goodsInfo.value,
					goods_sku_id: this.spGoodsInfo.goods_spec_id,
					coupon_id: this.couponInfo.id && this.couponInfo.id || '',
					type: payType,
					beizhu: this.beizhu,
					aid: this.addressInfo.address_id && this.addressInfo.address_id,
				}).then(res => {
					uni.hideLoading()
					if (res.code === 1) {
						if (payType === 'wx') {
							let pay = res.data
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: pay.timeStamp,
								nonceStr: pay.nonceStr,
								package: pay.package,
								signType: pay.signType,
								paySign: pay.paySign,
								success: (res) => { // 微信支付成功就跳转详情
									uni.showToast({
										title: res.msg,
										icon: 'success',
										mask: true
									})
									setTimeout(() => {
										this.pageJumps('/pages/mine/myOrderList')
									}, 600)
								},
								fail(err) {
									console.log('fail:' + JSON.stringify(err));
								}
							});
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								mask: true
							})
							setTimeout(() => {
								this.pageJumps('/pages/mine/myOrderList')
							}, 600)
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F5F5;
	}

	.container {
		padding-bottom: 98rpx;
	}
	.tui-btn-danger{
		background: #3d3d3d !important;
		border-radius: 0.5em;
	}
</style>
